<?php
namespace Admin\Models\log;

use Admin\Models\BaseModel;
use Helpers\Main;
use Helpers\Tool;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;
use Admin\Models\sys\XhsysConfig;

class LoginLog extends BaseModel
{

    /**
     *
     * @var integer
     * @Primary
     * @Identity
     * @Column(type="integer", length=20, nullable=false)
     */
    public $lo_id;

    /**
     *
     * @var integer
     * @Column(type="integer", length=20, nullable=false)
     */
    public $lo_us_id;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=false)
     */
    public $lo_uid;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=false)
     */
    public $lo_os;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=false)
     */
    public $lo_processor;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=false)
     */
    public $lo_computername;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=false)
     */
    public $lo_user_agent;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=false)
     */
    public $lo_ip;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=false)
     */
    public $lo_language;

    /**
     *
     * @var string
     * @Column(type="string", nullable=false)
     */
    public $lo_date;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $lo_mac;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $lo_model;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $lo_imei;

    /**
     * Initialize method for model.
     *  modify qgz 20180824 //login_log原来走配置取库表信息,改为直接用xh_webmanage库
     */
    public function initialize()
    {
	    parent::initialize();
//        parent::initialize();
//        $config = XhsysConfig::findFirst("sConfigName = 'oldCenterDB' AND bDelete = 0");
//        $configData = json_decode($config->mConfigValue);
//        $this->di->set(
//            'dbMysql',
//            function () use ($configData) {
//                return new MysqlPdo(
//                    [
//                        'host'     => $configData->host,
//                        'username' => $configData->username,
//                        'password' => $configData->password,
//                        'dbname'   => $configData->dbname,
//                        'charset'  => $configData->charset,
//                    ]
//                );
//            }
//        );
//
//        $this->setConnectionService('dbMysql');
//       $this->setSchema("xh_zjhzztxx_school");
//        $this->setSource("login_log");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'login_log';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return LoginLog[]|LoginLog|\Phalcon\Mvc\Model\ResultSetInterface
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return LoginLog|\Phalcon\Mvc\Model\ResultInterface
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * [search description]
     * @method search
     * @param  [type] $parameters [参数...]
     * @return [array]             [带有页数/总数/数据本身(数组)]
     * modify by ck 20181225
     */
    public static function search($parameters = null){
        $query = LoginLog::query()->columns('*')->orderby('lo_id desc');
        //$countquery = LoginLog::query()->columns('COUNT(*)')->distinct('lo_id');

//        $equalCols = [
//          [
//            'param' => 'name',
//            'field' => 'lo_uid',
//          ],
//          [
//            'param' => 'computer',
//            'field' => 'lo_computername',
//          ],
//            [
//                'param' => 'mac',
//                'field' => 'lo_mac',
//            ],
//        ];
//
//        foreach ($equalCols as $key => $value) {
//          if(isset($parameters[$value['param']])){
//            if($parameters[$value['param']] != ''){
//              $query->andWhere($value['field'].'= :'.$value['param'].':',[$value['param'] => trim($parameters[$value['param']])]);
//            }
//          }
//        }
        if (Tool::getValue($parameters, 'item') && Tool::getValue($parameters, 'itemValue')) {
            $query->andWhere(Tool::getValue($parameters, 'item') . ' = "' . trim(Tool::getValue($parameters, 'itemValue')) . '"');
        }


//        if(max(isset($parameters['maxtime']) ? $parameters['maxtime'] : 0,isset($parameters['mintime']) ? $parameters['mintime'] : 0)){
//          $timeArr = explode(',',$parameters['maxtime'].','.$parameters['mintime']);
//          if(!in_array('',$timeArr)){
//            $mintime = $parameters['mintime'];
//            $maxtime = $parameters['maxtime'];
//          }
//          else{
//            $mintime = $parameters['mintime'] ? $parameters['mintime'] : date('Y-m-d',26729452);
//            $maxtime = $parameters['maxtime'] ? $parameters['maxtime'] : date('Y-m-d',time());
//          }
//          $query->betweenWhere('lo_date',$parameters['mintime'],$parameters['maxtime']);
//        }

        //modify by ck 20171124
        if (isset($parameters['mintime']) && $parameters['mintime']) {
            $query->andWhere('lo_date >= :minTime:', ['minTime' => $parameters['mintime']]);
        }
        if (isset($parameters['maxtime']) && $parameters['maxtime']) {
            $query->andWhere('lo_date <= :maxTime:', ['maxTime' => date('Y-m-d', strtotime($parameters['maxtime'] . '+1 day'))]);
        }


        //$total = $countquery->execute()->toArray();
//        $newQuery = clone($query);
        $total = $query->columns('COUNT(*)')->execute()->toArray();
        $query = $query->columns('*');
        if(isset($parameters['page'])){
            $page = $parameters['page'];
        }
        else{
            $page = 1;
        }

        if(isset($parameters['rows'])){
            $rows = intval($parameters['rows']);
        }
        else{
            $rows = 10;
        }
        $query->limit($rows,($page-1)*$rows);

        $data = $query->execute();

        $newdata = $data->toArray();
        Main::runUserName($newdata, ['lo_us_id' => 'username']);
//       foreach ($data as $key => $val) {
//           //$newdata[$key]['username'] = $val->users->us_name;
//           $userData = Users::findFirst(['us_id = '.$val->lo_us_id]);
//           //return $val->lo_us_id;
//           if(!empty($userData)){
//               $newdata[$key]['username'] = $userData->us_name;
//           }
//           else{
//               $newdata[$key]['username'] = '';
//           }
//
//       }

        $result = array();
        $result['rows'] = $newdata;
        $result['total'] = $total[0];
        return $result;
    }

}
